{extend name="base" /}
<!-- page specific plugin styles -->
{block name="plugin-styles"}
    <link rel="stylesheet" href="/static/ace/assets/css/jquery-ui.custom.min.css" />
    <link rel="stylesheet" href="/static/ace/assets/css/chosen.min.css" />
    <link rel="stylesheet" href="/static/ace/assets/css/bootstrap-datepicker3.min.css" />
    <link rel="stylesheet" href="/static/plugin/UploadFive/uploadifive.css">
    <link href="https://cdn.bootcss.com/wangEditor/10.0.13/wangEditor.min.css" rel="stylesheet">
{/block}
<!-- inline styles related to this page -->
{block name="inline-styles"}
<style type="text/css">
    .close{
        float: none;
        opacity: .8;
        text-shadow: none;
        line-height: 1.5;
    }
</style>
{/block}
<!-- PAGE CONTENT BEGINS -->
{block name="content"}
<div class="page-header">
    <h1>
        商品修改
    </h1>
</div>
<!-- /.page-header -->
<form class="form-horizontal" id="ajaxForm">
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 产品缩略图 </label>
        <div class="col-sm-2">
            <input type="text" name="pic" placeholder="" id="pic" value='{$item.pic}'>
        </div>
        <div class="col-sm-5">
            <image src='{$item.pic}'width='100px'/>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 产品轮播图 </label>
        <div class="col-sm-2">
            <input type="text" name="multipic" placeholder="" id="multipic" value="{$item.multipic}">
        </div>
        <div class="col-sm-8">
            {foreach $item.pics as $vo}
            <div onclick="deletePic(this,'{$vo}')" class='col-sm-2' title='点击删除'><image src='{$vo}'width='100px'/></div>
            {/foreach}
        </div>  
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 名称 </label>
        <div class="col-sm-9">
            <input type="text" name="goodsname" placeholder="" value='{$item.goodsname}' class="col-xs-10 col-sm-5">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 优先级 </label>
        <div class="col-sm-9">
            <input type="text" name="orderby" placeholder="" value='{$item.orderby}' class="col-xs-10 col-sm-5">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 产品分类 </label>
        <div class="col-sm-9">
             <select name='catid'>
                {foreach $cates as $vo} 
                <option value={$vo.id} {if condition="$item['catid'] == $vo.id"} selected {/if}>{$vo.catname}</option>
                {/foreach}
            </select>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 商品类型 </label>
        <div class="col-sm-2">
             <select name='goods_type_id' id="goods_type_id" onchange='selectGoodsSpecs()'>
                <option value='0' {if condition="$item['goods_type_id'] == 0"} selected {/if}>-</option>
                {foreach $goods_types as $vo} 
                <option value={$vo.id} {if condition="$item['goods_type_id'] == $vo.id"} selected {/if}>{$vo.name}</option>
                {/foreach}
            </select>
        </div>
        <div class="col-sm-2">
            <a class='btn btn-sm btn-inverse' href='{:url('goods/goods_type')}' target='_blank'>添加商品类型</a>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 商品规格 </label>
        <div class="col-sm-5" id="attrList">
        {foreach $all_goods_specs as $vo}
            <p data-id="{$vo.id}">
            <span class="label label-success">{$vo.name}</span> &nbsp;&nbsp;
            {foreach $vo['values'] as $subvo}
                <span class="btn btn-minier btn-info" data-id="{$subvo.id}">{$subvo.item}</span>  &nbsp;&nbsp;
            {/foreach}
            </p>
        {/foreach}
        {if condition="$item['goods_type_id'] > 0"}
            <input type="text" placeholder="库存" class="col-sm-3" id="storeCount">
            <div class="col-sm-2"><input type="button" id="button1" class="btn btn-sm btn-inverse" onclick="addSpec()" value="添加" /></div>
        {/if}
        </div>
        <div class="col-sm-4">
            <table class="table table-bordered" id="attrSpe">
                <thead>
                    <tr>
                        <th>规格</th>
                        <th width="15%">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {foreach $item['spec_prices'] as $vo}
                    <tr>
                        <td>{$vo['key_name']} <input type="hidden" value='{$vo["item"]}'></td>
                        <td><button type="button" class="btn btn-mini btn-danger" onclick="delTr(this)">删除</button></td>
                    </tr>
                    {/foreach}
                </tbody>
            </table>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 仓库 </label>
        <div class="col-sm-1">
            <select name='store_id'>
                <option value="0"></option>
                {foreach $stores as $vo} 
                <option value={$vo.id} {if condition="$item['store_id'] == $vo.id"} selected {/if}>{$vo.name}</option>
                {/foreach}
            </select>
        </div>
        <div class="col-sm-2">
            <a href='{:url('goods/store')}'>添加仓库</a>
        </div>
    </div>
    
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 库存 </label>
        <div class="col-sm-9">
            <input type="text" name="stock" placeholder="" value='{$item.stock}' class="col-xs-10 col-sm-5">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 价格 </label>
        <div class="col-sm-9">
            <input type="text" name="price" placeholder="" value='{$item.price}' class="col-xs-10 col-sm-5">
        </div>
    </div>
     <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 供货价格 </label>
        <div class="col-sm-9">
            <input type="text" name="supply_price" placeholder="" value='{$item.supply_price}' class="col-xs-10 col-sm-5">
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 订单奖励 </label>
        <div class="col-sm-9">
            <input type="text" name="reward" placeholder="" value='{$item.reward}' class="col-xs-10 col-sm-5" size="8">
        </div>
    </div>
    <div class="form-group">
        <label for="" class="col-sm-2 control-label">定时上线</label>
        <div class="col-sm-4">
            <div class="input-group">
                <input name="online_time" id="onlineTime" type="text" value="{$item.online_date}" class="form-control" >
                <span class="input-group-addon">
                    <i class="fa fa-calendar bigger-110"></i>
                </span>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 是否限时 </label>
        <div class="col-sm-9">
            <label class="radio-inline">
                <input type="radio" name="is_time_limit" value="1" {if condition="$item['is_time_limit'] == 1"} checked="checked"{/if}> 是
            </label>
            <label class="radio-inline">
                <input type="radio" name="is_time_limit" value="0" {if condition="$item['is_time_limit'] == 0"} checked="checked"{/if}> 否
            </label>
        </div>
    </div>
    
    <div class="form-group">
        <label for="" class="col-sm-2 control-label">开始时间</label>
        <div class="col-sm-4">
            <div class="input-group">
                <input name="start_time" id="startTime" type="text" value="{$item.start_date}" class="form-control" >
                <span class="input-group-addon">
                    <i class="fa fa-calendar bigger-110"></i>
                </span>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label for="" class="col-sm-2 control-label">结束时间</label>
        <div class="col-sm-4">
            <div class="input-group">
                <input name="end_time" id="endTime" type="text" value="{$item.end_date}" class="form-control" data-date-format="YYYY-MM-DD HH:mm">
                <span class="input-group-addon">
                    <i class="fa fa-calendar bigger-110"></i>
                </span>
            </div>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 是否上架 </label>
        <div class="col-sm-9">
            <label class="radio-inline">
                <input type="radio" name="isshow" value="1" {if condition="$item['isshow'] == 1"} checked="checked"{/if}> 是
            </label>
            <label class="radio-inline">
                <input type="radio" name="isshow" value="2" {if condition="$item['isshow'] == 2"} checked="checked"{/if}> 否
            </label>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-2 control-label no-padding-right"> 详情 </label>
        <div class="col-sm-8">
            <textarea class="form-control hidden" name="detail"></textarea>
            <div id="formEditor">{$item.detail}</div>
        </div>
    </div>
    <div class="clearfix form-actions">
        <div class="col-md-offset-3 col-md-9">
            <button class="btn btn-info" type="button" id="showToast">
                <i class="ace-icon fa fa-check bigger-110"></i>
                Submit
            </button>

            &nbsp; &nbsp; &nbsp;
            <button class="btn" type="reset">
                <i class="ace-icon fa fa-undo bigger-110"></i>
                Reset
            </button>
        </div>
    </div>
</form>
{/block}
<!-- PAGE CONTENT ENDS -->
<!-- page specific plugin scripts -->
{block name="plugin-scripts"}
    <!--[if lte IE 8]>
      <script src="/static/assets/js/excanvas.min.js"></script>
    <![endif]-->
    <script src="/static/ace/assets/js/jquery-ui.custom.min.js"></script>
    <script src="/static/ace/assets/js/jquery.ui.touch-punch.min.js"></script>
    <script src="/static/ace/assets/js/bootstrap-datepicker.min.js"></script>
    <script src="/static/ace/assets/js/moment.min.js"></script>
    <script src="/static/ace/assets/js/daterangepicker.min.js"></script>
    <script src="/static/ace/assets/js/bootstrap-datetimepicker.min.js"></script>
    <script src="/static/plugin/UploadFive/jquery.uploadifive.min.js"></script>
    <script src="https://cdn.bootcss.com/wangEditor/10.0.13/wangEditor.min.js"></script>
{/block}
<!-- inline scripts related to this page -->
{block name="related-scripts"}
<script type="text/javascript">
    // 开始时间
    var ALL_GOODS_SPEC = '{$all_goods_specs|json_encode}';
    
    
    //上线时间
    $('#onlineTime').datetimepicker({
        format: 'YYYY-MM-DD HH:mm',//use this option to display seconds
    }).next().on(ace.click_event, function(){
        $(this).prev().focus();
    });
    
    $('#startTime').datetimepicker({
        format: 'YYYY-MM-DD HH:mm',//use this option to display seconds
    }).next().on(ace.click_event, function(){
        $(this).prev().focus();
    });
                
    
    // 结束时间
    $('#endTime').datetimepicker({
        format: 'YYYY-MM-DD HH:mm',//use this option to display seconds
    }).next().on(ace.click_event, function(){
        $(this).prev().focus();
    });
    
    // function addSpec(){
    //     alert('xxx')
    // }
    
    function selectGoodsSpecs(){
        goods_type_id = $('#goods_type_id').val()
        $.get("/admin/goods/goods_spec_list",{ goods_type_id: goods_type_id} ,
            function(result){
                console.log(result);
                renderAttr(result.data);
            }
        );
    }


    $('#pic').uploadifive({
        // 'width'        : 77,
        'height'       : 'auto',
        'buttonClass'  : 'btn btn-xs btn-primary',
        'buttonText'   : '上传图片',
        // 'queueID'      : 'uploaderFiles',
        // 'itemTemplate' : '<li class="uploadifive-queue-item"><a data-rel="colorbox" class="cboxElement"></a><div class="tags"><span class="label-holder"><span class="label label-info">100%</span></span></div><div class="tools tools-bottom"><a class="close"><i class="ace-icon fa fa-times red"></i></a></div></li>',
        'auto'         : true, //自动上传
        'fileObjName'  : 'image',
        'fileSizeLimit': 10240,
        'fileType'     : 'image/*',
        'method'       : 'post',
        'formData'     : {'someKey' : 'someValue'},
        'uploadScript' : '/api/v1/tools/upload',
        'multi'        : false,
        'overrideEvents' : ['onProgress'],
        'queueSizeLimit' : 2,
        'removeCompleted' : false,  //删除已上传的队列
        'simUploadLimit' : 0,   //同时上传的文件数
        'truncateLength' : 0,   //截断队列中文件名的字符数
        'uploadLimit'  : 0, //可以上传的最大文件数
        'onInit'       : function() {
            console.log('onInit:将文件添加到队列中开始上传.');
        },
        'onUploadComplete' : function(file, data) {
            var _json= JSON.parse(data);
            $("input[name=pic]").val(_json.data.url);
        },
        'onFallback'   : function() {
            alert('Oops!  You have to use the non-HTML5 file uploader.');
        }
    });

    var _multiple=JSON.parse('{$item.pics_json}');
    $('#multipic').uploadifive({
        // 'width'        : 77,
        'height'       : 'auto',
        'buttonClass'  : 'btn btn-xs btn-primary',
        'buttonText'   : '上传图片',
        // 'queueID'      : 'uploaderFiles',
        // 'itemTemplate' : '<li class="uploadifive-queue-item"><a data-rel="colorbox" class="cboxElement"></a><div class="tags"><span class="label-holder"><span class="label label-info">100%</span></span></div><div class="tools tools-bottom"><a class="close"><i class="ace-icon fa fa-times red"></i></a></div></li>',
        'auto'         : true, //自动上传
        'fileObjName'  : 'image',
        'fileSizeLimit': 10240,
        'fileType'     : 'image/*',
        'method'       : 'post',
        'formData'     : {'someKey' : 'someValue'},
        'uploadScript' : '/api/v1/tools/upload',
        'multi'        : true,
        'overrideEvents' : ['onProgress'],
        'queueSizeLimit' : 10,
        'removeCompleted' : false,  //删除已上传的队列
        'simUploadLimit' : 0,   //同时上传的文件数
        'truncateLength' : 0,   //截断队列中文件名的字符数
        'uploadLimit'  : 0, //可以上传的最大文件数
        'onInit'       : function() {
            console.log('onInit:将文件添加到队列中开始上传.');
        },
        'onUploadComplete' : function(file, data) {
            var _json= JSON.parse(data);
            _multiple.push(_json.data.url);
            $("input[name=multipic]").val(_multiple.join(","));
        },
        'onFallback'   : function() {
            alert('Oops!  You have to use the non-HTML5 file uploader.');
        }
    });

    $("#showToast").click(function(event) {
        /* Act on the event */
        var _attr = [];
        $("#attrSpe tbody").find('tr').each(function() {
            // body...
            _item = $(this).find('input').val();
            _attr.push(_item);
        })
        console.log(_attr);
        var options={
            url:"/admin/goods/add_or_update",
            type:"POST",
            dataType:"json",
            data: {
                id : GetQueryString("id"),
                attr:_attr
            },
            success: function(json){

                if(json.returnCode==1){
                    alert('保存成功');
                    window.location=document.referrer;
                }else{
                    alert(json.returnMsg);
                }
            }
        };
        $("#ajaxForm").ajaxSubmit(options)
    });
    
    function deletePic(_ele,pic){
        console.log(pic)
        
        $(_ele).remove();
        _multiple.splice($.inArray(pic,_multiple),1); 
    }
    
 // 编辑器
    var E = window.wangEditor;
    var editor = new E('#formEditor');
    var $text1 = $('textarea[name=detail]');
    editor.customConfig.zIndex = 100;
    editor.customConfig.uploadImgServer = '/admin/tools/upload_image';
    editor.customConfig.uploadFileName = 'image[]'
    editor.customConfig.onchange = function (html) {
        // 监控变化，同步更新到 textarea
        $text1.val(html)
    };
   editor.create();
    // 初始化 textarea 的值
    $text1.val(editor.txt.html());


    // 初始化规格操作
    $("#attrList").find('.btn').click(function(event) {
        /* Act on the event */
        $(this).addClass('btn-danger').removeClass('btn-info').siblings('.btn').removeClass('btn-danger').addClass('btn-info');
    });
    // 渲染规格
    function renderAttr(data) {
        // body..
        $("#attrList").empty();
        for (var i = 0; i < data.length; i++) {
        	var _item = $('<p data-id="'+data[i].id+'"><span class="label label-success">'+data[i].name+'</span> &nbsp;&nbsp; </p>');
            for (var n = 0; n < data[i].values.length; n++) {
                _item.append('<span class="btn btn-minier btn-info" data-id="'+data[i].values[n].id+'">'+data[i].values[n].item+'</span> &nbsp;&nbsp;');
            }
            $("#attrList").append(_item);
            $("#attrList").find('.btn').click(function(event) {
                /* Act on the event */
                $(this).addClass('btn-danger').removeClass('btn-info').siblings('.btn').removeClass('btn-danger').addClass('btn-info');
            });
        }
        if(data.length>0){
        	$("#attrList").append('<input type="text" placeholder="库存" class="col-sm-3" id="storeCount">');
            $("#attrList").append('<div class="col-sm-2"><input type="button" id="button1" class="btn btn-sm btn-inverse" onclick="addSpec()" value="添加" /></div>');
        }
        
    }

    // 添加规格
    function addSpec() {
        // body...
        var _spe ='';
        var _jsonItem ={
            item:[],
            store_count: $('#storeCount').val()
        };
        $("#attrList").find('.btn-danger').each(function(){
            var _item = {
                id : $(this).parents('p').data('id'),
                value: $(this).data('id')
            };
            _jsonItem.item.push(_item);
            _spe = _spe + $(this).parents('p').find('.label').text() + ':' + $(this).text() + ',';
        });
        _spe = _spe + '库存:'+ $('#storeCount').val();
        var _tr = 
            '<tr>\
                <td>'+_spe+'<input type="hidden" value='+JSON.stringify(_jsonItem)+'></td>\
                <td>\
                    <button type="button" class="btn btn-mini btn-danger" onclick="delTr(this)">删除</button>\
                </td>\
            </tr>';
        $("#attrSpe").append(_tr);
        $("#attrList").find('.btn').each(function(){
            $(this).addClass('btn-info').removeClass('btn-danger');
        });
        $('#storeCount').val('');
    }

    // 删除规格
    function delTr(e) {
        // body...
        $(e).parents('tr').remove();
    }
</script>
{/block}